<script setup lang="ts">
import { ref, onMounted, watch, nextTick} from 'vue'
import { GetAllClusterConfig } from "@/api/cluster";
// 推荐使用 Naive UI 卡片组件
import { NCard, NSpin, NDivider, NPopover, NTag, NTabs, NTabPane, NButton, NIcon } from 'naive-ui'
// icon - 修改导入方式
import { ArrowEnterLeft20Filled } from '@vicons/fluent'
import { defineProps, reactive } from 'vue'
import { AddClusterConfig } from "@/api/cluster";
import { message } from 'ant-design-vue'
// 修正导入方式 - 使用默认导入
import router from "@/router";
import { useNavStore } from "@/store/nav.ts";

export interface Cluster {
  name: string
  status: 'Ready' | 'NotReady'
  clusterVersion: string
  nodes: NodeInfo[]
  id: number
  namespaces: string[] // 新增命名空间数组
}

interface NodeInfo {
  name: string
  ip: string
  status: string
  role: string
}

// const clusterTypeNameMap = {
//   core: '核心云',
//   edge: '边缘云',
// }

// 入参 props，假设为 filter，类型和用途请根据实际调整
const props = defineProps<{
  clusterType: 'core' | 'edge'
}>()

const clusters = ref<Cluster[]>([])
const loading = ref(false)
const addNewClusterModalOpen = ref(false)

const cardRefs = ref<HTMLElement[]>([])

const cardOnClick = async (cluster: Cluster) => {
  console.log(`点击了集群: ${cluster.name}`)
}

// const openAddNewClusterModal = () => {
//   addNewClusterModalOpen.value = true
// }

const onSubmitModal = async () => {
  console.log('提交添加新集群:', addClusterState)
  // 调用提交数据的api
  let res = await AddClusterConfig({
    name: addClusterState.name,
    cluster_type: addClusterState.type,
    kube_config_content: addClusterState.kube_config,
  })
  if (res.code === 0) {
    message.success('集群添加成功')
    // 清空数据
    addClusterState.name = ''
    addClusterState.type = props.clusterType
    addClusterState.kube_config = ''
    addNewClusterModalOpen.value = false
  } else {
    message.error(`集群添加失败: ${res.message}`)
  }
}

const onCancelModal = () => {
  // 数据清空
  // addClusterState.value = {
  //   name: '',
  //   type: props.clusterType,
  //   kube_config: '',
  // }
  addNewClusterModalOpen.value = false
}

const addClusterState = reactive({
  name: '',
  type: props.clusterType,
  kube_config: '',
  // 其他需要的字段
})

const onFinish = async () => {
  await onSubmitModal();
};

const onFinishFailed = () => {

};

const navStore = useNavStore();

// 点击进入集群后的函数，该函数会修改路由
const enterCluster = (clusterID: number) => {
  // 在导航前设置 clusterId
  navStore.currentClusterId = String(clusterID);
  // 这里可以添加跳转逻辑，比如使用路由跳转到集群详情页
  router.push({name: 'cluster-overview', params: { clusterId: clusterID }})
}

// 模板函数：根据 props.filter 获取集群信息
async function fetchClusters() {
  loading.value = true
  let { data } = await GetAllClusterConfig(props.clusterType)
  // 添加模拟的命名空间数据
  clusters.value = data.map((item: any) => {
    return {
      id: item.id,
      name: item.name,
      status: item.status,
      clusterVersion: item.kube_version,
      nodes: item.node,
      namespaces: (item.namespaces || []).map((ns: any) => ns.name),
    } as Cluster
  })
  loading.value = false
}

onMounted(fetchClusters)

watch(() => props.clusterType, fetchClusters)

watch(clusters, () => {
  nextTick(() => {
    cardRefs
    emit('coreCard-mounted', { cardEls: cardRefs.value })
})}
)

// 节点标签点击事件模板
function nodeTagClick(node: NodeInfo) {
  console.log('点击了节点标签', node)
}

// 命名空间标签点击事件模板
function namespaceTagClick(cluster: Cluster, namespace: string) {
  console.log(`点击了集群 ${cluster.name} 中的命名空间 ${namespace}`)
  // 后续这里可以处理点击命名空间后的页面转换逻辑
}


// function setCardRef(id: string, el: Element | null) {
//   if (el instanceof HTMLElement) {
//     emit('card-mounted', { id: String(id), el })
//   }
// }

const emit = defineEmits<{
  (e: 'coreCard-mounted', payload: { cardEls:HTMLElement[]}): void
}>()

</script>

<template>
  <n-spin :show="loading">
    <div class="cluster-card-row">
      <template v-for="cluster in clusters" :key="cluster.name">
        <n-popover trigger="hover" placement="bottom" :width="380">
          <template #trigger>
            <div
              ref="cardRefs"
              :data-id=cluster.id
            >
              <n-card
                  hoverable
                  @click="cardOnClick(cluster)"
                  class="cluster-card"
                  :class="{
                  'cluster-ready': cluster.status === 'Ready',
                  'cluster-notready': cluster.status === 'NotReady'
                }"
              >
                <div class="cluster-card-content">
                  <div class="cluster-name">{{ cluster.name }}</div>
                  <img class="k8s-icon" src="/kubernetes.svg" alt="k8s"/>
                </div>
                <n-divider dashed class="cluster-card-divider"/>
                <div class="cluster-info-row">
                  <span class="cluster-version-badge">{{ cluster.clusterVersion }}</span>
                </div>
                <div class="cluster-info-row">
                  <span
                      class="cluster-status-badge"
                      :class="{
                      'status-ready': cluster.status === 'Ready',
                      'status-notready': cluster.status === 'NotReady'
                    }"
                  >
                    {{ cluster.status === 'Ready' ? 'Ready' : 'NotReady' }}
                  </span>
                </div>
              </n-card>
            </div>
          </template>

          <n-tabs type="line" size="small" animated>
            <n-tab-pane name="nodes" tab="节点">
              <div class="popover-node-list">
                <div class="popover-table">
                  <!-- 表头 -->
                  <div class="popover-header">
                    <div class="col col-name">节点名称</div>
                    <div class="col col-role">角色</div>
                    <div class="col col-ip">IP</div>
                    <div class="col col-status">状态</div>
                  </div>
                  <!-- 节点行 -->
                  <div
                      v-for="node in cluster.nodes"
                      :key="node.name"
                      class="popover-row"
                  >
                    <div class="col col-name">
                      <n-tag
                          type="info"
                          size="small"
                          class="popover-tag"
                          @click.stop="() => nodeTagClick(node)"
                      >
                        {{ node.name }}
                      </n-tag>
                    </div>
                    <div class="col col-role">
                      <n-tag
                          type="success"
                          size="small"
                          class="popover-tag"
                      >
                        {{ node.role }}
                      </n-tag>
                    </div>
                    <div class="col col-ip">
                      <n-tag
                          type="default"
                          size="small"
                          class="popover-tag"
                      >
                        {{ node.ip }}
                      </n-tag>
                    </div>
                    <div class="col col-status">
                      <n-tag
                          :type="node.status === 'Ready' ? 'success' : 'warning'"
                          size="small"
                          class="popover-tag"
                      >
                        {{ node.status }}
                      </n-tag>
                    </div>
                  </div>
                </div>
              </div>
            </n-tab-pane>

            <n-tab-pane name="namespaces" tab="命名空间">
              <div class="popover-namespace-list">
                <div class="namespace-grid">
                  <n-tag
                      v-for="ns in cluster.namespaces"
                      :key="ns"
                      type="primary"
                      size="small"
                      class="namespace-tag"
                      @click.stop="() => namespaceTagClick(cluster, ns)"
                  >
                    {{ ns }}
                  </n-tag>
                </div>
              </div>
            </n-tab-pane>
          </n-tabs>
          <div class="popover-footer">
            <n-button type="info" size="small" @click="enterCluster(cluster.id)">
              进入集群
              <n-icon>
                <ArrowEnterLeft20Filled/>
              </n-icon>
            </n-button>
          </div>
        </n-popover>
      </template>
      <!-- <n-card
        key="added"
        hoverable
        @click="openAddNewClusterModal"
        class="cluster-card cluster-adding"
      >
        <div class="cluster-card-content">
          <div class="cluster-name">+添加集群</div>
          <img class="k8s-icon" src="/kubernetes.svg" alt="k8s"/>
        </div>
      </n-card> -->
    </div>
  </n-spin>
  <a-modal
      v-model:open="addNewClusterModalOpen"
      title="添加新集群"
      :footer="null"
      width="800px"
  >
    <div>
      <a-form
          :model="addClusterState"
          name="addClusterForm"
          :label-col="{span: 6}"
          :wrapper-col="{span: 16}"
          autocomplete="off"
          @finish="onFinish"
          @finishFailed="onFinishFailed"
      >
        <a-form-item
            label="集群名称"
            name="name"
            :rules="[{required: true, message: '请输入集群名称'}]"
        >
          <a-input v-model:value="addClusterState.name"/>
        </a-form-item>
        <a-form-item
            label="集群类型"
            name="type"
        >
          <a-input v-model:value="addClusterState.type" disabled/>
        </a-form-item>
        <a-form-item
            label="kubeconfig"
            name="kube_config"
            :rules="[{required: true, message: '请输入kubeconfig内容'}]"
        >
          <a-textarea style="overflow: auto" v-model:value="addClusterState.kube_config"/>
        </a-form-item>
        <a-form-item :wrapper-col="{span: 14, offset:4}">
          <a-button type="primary" html-type="submit">提交</a-button>
          <a-button style="margin-left: 10px" @click="onCancelModal">取消</a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<style scoped>
.cluster-card-row {
  display: flex;
  flex-direction: row;
  gap: 16px;
  overflow-x: auto;
  padding-bottom: 8px;
}

.cluster-card {
  min-width: 180px;
  max-width: 220px;
  min-height: 160px;
  border-radius: 14px;
  border: 1.5px solid #3b82f622;
  box-shadow: 0 2px 12px 0 rgba(59, 130, 246, 0.08), 0 1.5px 6px 0 rgba(0, 0, 0, 0.06);
  background: #fff;
  transition: box-shadow 0.2s, background 0.2s;
  padding: 0;
}

.cluster-card:hover {
  box-shadow: 0 4px 24px 0 rgba(59, 130, 246, 0.18), 0 2px 8px 0 rgba(0, 0, 0, 0.10);
  border-color: #3b82f655;
  cursor: pointer;
}

.cluster-ready {
  background: #e8f8f2; /* 柔和绿色 */
}

.cluster-notready {
  background: #fff8e1; /* 柔和深黄色 */
}

/* .cluster-adding {
  background: #bfd9f5; //柔和蓝色 
}
*/

.cluster-card-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px 2px 12px;
  height: 36px;
}

.cluster-name {
  font-size: 1.08rem;
  font-weight: 500;
  color: #222;
  text-align: left;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.k8s-icon {
  width: 32px;
  height: 32px;
  margin-left: 12px;
  flex-shrink: 0;
}

.cluster-info-row {
  display: flex;
  align-items: center;
  margin-left: 12px;
  margin-top: 2px;
  margin-bottom: 2px;
}

.cluster-version-badge {
  display: inline-block;
  padding: 2px 10px;
  border-radius: 12px;
  background: #f3f4f6;
  color: #555;
  font-size: 0.92rem;
  font-weight: 400;
  letter-spacing: 0.5px;
}

.cluster-status-badge {
  display: inline-block;
  padding: 2px 12px;
  border-radius: 12px;
  font-size: 0.92rem;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.status-ready {
  background: #e6f9ed;
  color: #1a7f4f;
  border: 1px solid #b6e7ce;
}

.status-notready {
  background: #fff3cd;
  color: #b8860b;
  border: 1px solid #ffe082;
}

.cluster-card-divider {
  background-color: black;
  margin-top: 10px;
  margin-bottom: 10px;
  padding-left: 3px;
  padding-right: 3px;
}

.popover-node-list,
.popover-namespace-list {
  display: flex;
  flex-direction: column;
  width: 100%;
  max-height: 400px;
  padding: 8px 0;
  overflow-y: auto;
}

.popover-table {
  display: table;
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 4px;
}

.popover-header {
  display: table-row;
  font-size: 12px;
  color: #999;
  font-weight: 500;
}

.popover-row {
  display: table-row;
}

.col {
  display: table-cell;
  padding: 2px 4px;
  vertical-align: middle;
  text-align: left;
}

.col-name {
  width: 35%;
}

.col-role {
  width: 20%;
}

.col-ip {
  width: 25%;
}

.col-status {
  width: 20%;
}

.popover-tag {
  cursor: pointer;
  user-select: none;
  white-space: nowrap;
}

/* 命名空间网格布局 */
.namespace-grid {
  display: grid;
  grid-template-columns: 1fr; /* 修改为单列布局 */
  gap: 8px;
  width: 100%;
  justify-items: start; /* 强制左对齐 */
  overflow-y: auto;
}

.namespace-tag {
  cursor: pointer;
  user-select: none;
  white-space: nowrap;
  justify-self: start; /* 强制每个项目左对齐 */
  width: fit-content; /* 使标签宽度适应内容 */
  max-width: 100%;
}

.popover-footer {
  display: flex;
  justify-content: flex-end;
  padding: 8px;
  border-top: 1px solid #e8e8e8;
}
</style>

